using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace GoldStone.Common.Utils {
    public static class NetUtil {
        public static readonly String LocalHostName = Dns.GetHostName();

        //static NetUtil() {
        //    ServicePointManager.DefaultConnectionLimit = Settings.Default.DefaultConnectionLimit;
        //}

        private static readonly Regex charsetRegex = new Regex("<meta http-equiv(.*)charset=(?<charset>.*)", RegexOptions.IgnoreCase);
        private static readonly CookieContainer Cookies = new CookieContainer();

        public static bool IsDefaultCharset(String encoding) {
            String upper = encoding.ToUpper();
            return upper == "UTF-8" || upper == "UTF8";
        }

        public static String GetCharset(String htmlContent) {
            string charstring = RegexUtil.FirstMatch(htmlContent, charsetRegex, "charset", "UTF-8");
            return charstring.Split('\'', '"', ' ', '/', '>')[0];
        }

        public static String GetContent(String URL) {
            String content = GetContent(URL, Encoding.UTF8);
            String charset = GetCharset(content);
            if (IsDefaultCharset(charset)) {
                return content;
            }
            return GetContent(URL, Encoding.GetEncoding(charset));
        }

        public static String GetContent(String URL, Encoding encode) {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(URL);
            request.CookieContainer = Cookies;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP 5.1)";
            //request.Headers["Accept-Language"] = "zh-CN";
            //request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5";
            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse()) {
                Cookies.Add(response.Cookies);
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encode)) {
                    String result = "";
                    Char[] buffer = new Char[1024];
                    int count = reader.Read(buffer, 0, buffer.Length);
                    while (count > 0) {
                        result += new String(buffer, 0, count);
                        count = reader.Read(buffer, 0, buffer.Length);
                    }
                    reader.Close();
                    response.Close();
                    return result;
                }
            }
        }

        public static bool IsInternalUrl(String url, String root) {
            Uri uri = new Uri(url.ToLower());
            Uri rooti = new Uri(root.ToLower());
            if (!IsSameHost(uri.Host, rooti.Host)) {
                return false;
            }
            return uri.AbsolutePath.StartsWith(rooti.AbsolutePath);
        }

        public static bool IsSameHost(String host1, String host2) {
            IPAddress[] ips1 = Dns.GetHostEntry(host1).AddressList;
            IPAddress[] ips2 = Dns.GetHostEntry(host2).AddressList;
            return Array.Exists(ips1, delegate(IPAddress ip1) {
                                          return Array.Exists(ips2, delegate(IPAddress ip2) {
                                                                        return ip1.ToString().Equals(ip2.ToString());
                                                                    });
                                      });
        }
    }
}